package com.threez.stream.ibm.config.connect;


import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import com.threez.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter;
import org.springframework.jms.core.JmsTemplate;

@Slf4j
@EnableConfigurationProperties({IbmMqConnect.class})
@ConditionalOnProperty(prefix = "spring.cloud.stream", value = "default-binder",havingValue = "ibmsingle")
@AutoConfiguration
public class JmsTemplateConfig {


    @Bean
    public UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter(IbmMqConnect ibmMqConnect){
        MQQueueConnectionFactory mqQueueConnectionFactory = new MQQueueConnectionFactory();
        mqQueueConnectionFactory.setHostName(ibmMqConnect.getHost());
        try {
            mqQueueConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
            mqQueueConnectionFactory.setCCSID(1208);
            mqQueueConnectionFactory.setChannel(ibmMqConnect.getChannel());
            mqQueueConnectionFactory.setPort(ibmMqConnect.getPort());
            mqQueueConnectionFactory.setQueueManager(ibmMqConnect.getQueueManager());
        } catch (Exception e) {
            log.error("链接异常", e);
        }
        UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
        userCredentialsConnectionFactoryAdapter.setUsername(ibmMqConnect.getUserName());
        userCredentialsConnectionFactoryAdapter.setPassword(ibmMqConnect.getPassword());
        userCredentialsConnectionFactoryAdapter.setTargetConnectionFactory(mqQueueConnectionFactory);
        return userCredentialsConnectionFactoryAdapter;
    }

    @Bean("pointJmsTemplate")
    public JmsTemplate jmsOperations(UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter) {
        IbmMqConnect ibmMqConnect = SpringUtils.getBean(IbmMqConnect.class);
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setTargetConnectionFactory(userCredentialsConnectionFactoryAdapter);
        cachingConnectionFactory.setSessionCacheSize(500);
        cachingConnectionFactory.setReconnectOnException(true);
        JmsTemplate jmsTemplate = new JmsTemplate(cachingConnectionFactory);
        jmsTemplate.setReceiveTimeout(ibmMqConnect.getReceiveTimeout());
        return jmsTemplate;
    }

}
